//
//  HYUserAccountViewModel.swift
//  WeiBo
//
//  Created by crazyfish on 16/3/14.
//  Copyright © 2016年 crazyfish. All rights reserved.
//

import UIKit
class HYUserAccountViewModel: NSObject {
    
    var userlogon: Bool {
    
    //判断用户是否登录(判断用户是否登录过了且生命周期没有过期)
    //1.是否有accesstoken
    
        if self.accessToken != nil && !isExpiresIn{
            
            return true
        }

    
    //2.accesstoken是否过期
   return false
    
}
    //用户是否登录,accesstoken是否存在
    var accessToken: String? {
        return account?.access_token
    }
    
    //判断当前账户的accesstoken是否过期,如果过期返回true
    var isExpiresIn: Bool{
        
        if NSDate().compare(account!.expiresDate!) == .OrderedAscending{
            
            return false
        }
        
        return true
    }
    
    
    //当前模型视图引用的模型
    var account:HYUserAccount?

    //创建单例对象
    static let sharedAccountViewModel: HYUserAccountViewModel = {
    
        let vm = HYUserAccountViewModel()
        
        //获取路径
        let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.achive")
        //去解档
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? HYUserAccount
        //赋值
        vm.account = result
        
        return vm
    
    }()
    
    
    //获取访问令牌的方法
    func loadAccessToken(code: String,callback:(isSuccess: Bool)->()){
        
        //请求地址
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        /**
         *   	必选 	类型及范围 	说明
         client_id 	true 	string 	申请应用时分配的AppKey。
         client_secret 	true 	string 	申请应用时分配的AppSecret。
         grant_type 	true 	string 	请求的类型，填写authorization_code
         
         
         grant_type为authorization_code时
         
         必选 	类型及范围 	说明
         code 	true 	string 	调用authorize获得的code值。
         redirect_uri 	true 	string 	回调地址，需需与注册应用里的回调地址一致。
         
         */
         
         
         //请求参数
        let parameters = [
            
            "client_id": WB_APPKEY,
            
            "client_secret": WB_APPSECRET,
            
            "grant_type": "authorization_code",
            
            "code": code,
            
            "redirect_uri": WB_REDIRRECT_URL
            
        ]
        
        //发送请求
        
        HYNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil{
                
                callback(isSuccess: false)
                
                return
            }
            
            //进行字典转模型,并且获取个人信息
            
            let account = HYUserAccount(dict:responseObject!)
            
            self.account = account
            
            self.loadUserInfo(account,callback:callback)
            
          
        }
        
    }
    
    private func loadUserInfo(account: HYUserAccount,callback:(isSuccess: Bool)->() ){
        
        //1.定义URLStr
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //2.定义参数
        
        //参数不够
        guard let accessToken = account.access_token, let uid = account.uid else{
            callback(isSuccess: false)
            return
        }
        
        //        let accessToken = account.access_token!
        //
        //        let uid = account.uid!
        
        let parameters = ["access_token": accessToken,
            "uid":uid
        ]
        
        //3.发送请求
        HYNetworkTools.sharedTools.requst(.GET, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            //登录失败
            if error != nil{
                
                callback(isSuccess: false)
               //   SVProgressHUD.showErrorWithStatus("个人信息获取失败")
                
                return
            }
            
            print(responseObject)
            
            //把用户的别名和头像保存到模型里面
            account.screen_name = responseObject!["screen_name"] as? String
            account.avatar_large = responseObject!["avatar_large"] as? String
            
            //归档
            //file是存储路径.拼接的时候要主要使用的方法是stringByAppendingPathComponent
            let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.achive")
            NSKeyedArchiver.archiveRootObject(account, toFile: file)
            
         
            
            //回调闭包,说明登录成功
             callback(isSuccess: true)
        }

    }
}
